//
//  ViewController.m
//  Peso Guide
//
//  Created by macbook on 2025/6/5.
//

#import "ViewController.h"
#import <Network/Network.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import "AppStarPre.h"
#import "FBSDKCoreKit/FBSDKCoreKit.h"
#import "NetworkStatusManager.h"
#import "IDFAUtils.h"
#import "GuideViewController.h"

@interface ViewController (){
    nw_path_monitor_t _pathMonitor;
    BOOL _hasNetworkPermission;
    BOOL _isLoginInitDone;
    NSString *FacebookAppID;
    NSString *CFBundleURLScheme;
    NSString *FacebookDisplayName;
    NSString *FacebookClientToken;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *backImg = [PesoKit createImageViewWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) imageNamed:@"app_launch"];
    [self.view addSubview:backImg];
    
    NSString *lang = [Lang language];
    NSString *modifying = [NetworkStatusManager proxyStatusString]==YES?@"1":@"0";
    NSString *vpn = [NetworkStatusManager isVPNConnected]==YES?@"1":@"0";
    
    [[AWHttpService service] postWithUrl:@"/trains/incorrect" params:@{@"incorrect":lang,@"modifying":modifying,@"self":vpn} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *associating = [responseObject safeObjectForKey:@"associating"];
                NSDictionary *inaccurate = [associating safeObjectForKey:@"inaccurate"];
                NSDictionary *synonymous = [associating safeObjectForKey:@"synonymous"];

                //  1=默认印度(审核面)   2=菲律宾(用户面)  后续请求放在公参里面
                NSString *narrowly = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"narrowly"]];
                self->FacebookAppID = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"bases"]];
                self->CFBundleURLScheme = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"formally"]];
                self->FacebookDisplayName = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"versus"]];
                self->FacebookClientToken = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"notes"]];
                //手机区号
                NSString *import = [NSString stringWithFormat:@"%@",[synonymous safeObjectForKey:@"import"]];
                //  【重要】1=弹出位置引导框   2=不弹 (场景：启动拒绝定位权限时，登陆后首页是否弹出位置引导弹窗，一天一次)
                NSString *engine = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"engine"]];
                // 隐私协议
                NSString *jinja = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"jinja"]];

                [[NSUserDefaults standardUserDefaults] setObject:narrowly forKey:@"user_country"];
                [[NSUserDefaults standardUserDefaults] setObject:import forKey:@"user_phone_start"];
                [[NSUserDefaults standardUserDefaults] setObject:jinja forKey:@"user_yinsi"];
                [[NSUserDefaults standardUserDefaults] setObject:engine forKey:@"user_show_location"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
            });
        }else {
            
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        
    }];
    
    // 开始网络权限检查流程
    [self startNetworkPermissionCheck];
}

#pragma mark - 网络权限检查
- (void)startNetworkPermissionCheck {
    // 创建网络路径监视器
    _pathMonitor = nw_path_monitor_create();
    if (!_pathMonitor) return;
    
    nw_path_monitor_set_queue(_pathMonitor, dispatch_get_main_queue());
    nw_path_monitor_set_update_handler(_pathMonitor, ^(nw_path_t path) {
        nw_path_status_t status = nw_path_get_status(path);
        
        if (status == nw_path_status_satisfied) {
            // 有网络权限
            self->_hasNetworkPermission = YES;
            [self startLoginInitialization];
        } else if (status == nw_path_status_unsatisfied) {
            // 无网络权限
//            [self gotoHomeScreen];
        }
        // 其他状态不处理
    });
    
    // 开始监控（会触发系统弹窗）
    nw_path_monitor_start(_pathMonitor);
}

#pragma mark - 登录初始化
- (void)startLoginInitialization {
    if (!_hasNetworkPermission || _isLoginInitDone) return;
    
    // 调用登录接口
    [self callLoginAPIWithCompletion:^(BOOL success) {
        if (success) {
            // 初始化Facebook SDK
            FBSDKSettings.sharedSettings.appID = self->FacebookAppID;
            FBSDKSettings.sharedSettings.clientToken = self->FacebookClientToken;
            FBSDKSettings.sharedSettings.displayName = self->FacebookDisplayName;
            FBSDKSettings.sharedSettings.appURLSchemeSuffix = self->CFBundleURLScheme;
            [[FBSDKApplicationDelegate sharedInstance] application:self.application didFinishLaunchingWithOptions:self.launchOptions];

            self->_isLoginInitDone = YES;
            [self requestIDFAPermission];
        } else {
//            [self gotoHomeScreen];
        }
    }];
}

- (void)callLoginAPIWithCompletion:(void (^)(BOOL))completion {
    
    NSString *lang = [Lang language];
    NSString *modifying = [NetworkStatusManager proxyStatusString]==YES?@"1":@"0";
    NSString *vpn = [NetworkStatusManager isVPNConnected]==YES?@"1":@"0";

    [[AWHttpService service] postWithUrl:@"/trains/incorrect" params:@{@"incorrect":lang,@"modifying":modifying,@"self":vpn} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *associating = [responseObject safeObjectForKey:@"associating"];
                NSDictionary *inaccurate = [associating safeObjectForKey:@"inaccurate"];
                NSDictionary *synonymous = [associating safeObjectForKey:@"synonymous"];

                //  1=默认印度(审核面)   2=菲律宾(用户面)  后续请求放在公参里面
                NSString *narrowly = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"narrowly"]];
                self->FacebookAppID = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"bases"]];
                self->CFBundleURLScheme = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"formally"]];
                self->FacebookDisplayName = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"versus"]];
                self->FacebookClientToken = [NSString stringWithFormat:@"%@",[inaccurate safeObjectForKey:@"notes"]];
                //手机区号
                NSString *import = [NSString stringWithFormat:@"%@",[synonymous safeObjectForKey:@"import"]];
                //  【重要】1=弹出位置引导框   2=不弹 (场景：启动拒绝定位权限时，登陆后首页是否弹出位置引导弹窗，一天一次)
                NSString *engine = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"engine"]];
                // 隐私协议
                NSString *jinja = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"jinja"]];

                [[NSUserDefaults standardUserDefaults] setObject:narrowly forKey:@"user_country"];
                [[NSUserDefaults standardUserDefaults] setObject:import forKey:@"user_phone_start"];
                [[NSUserDefaults standardUserDefaults] setObject:jinja forKey:@"user_yinsi"];
                [[NSUserDefaults standardUserDefaults] setObject:engine forKey:@"user_show_location"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                completion(YES);
            });
        }else {
            completion(NO);
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        completion(NO);
    }];
}

#pragma mark - IDFA权限请求
- (void)requestIDFAPermission {
    [IDFAUtils requestIDFAPermissionWithCompletion:^(NSString *idfa, BOOL isTrackingAuthorized) {
        if (isTrackingAuthorized && idfa.length > 0) {
            [AppTools saveIDFA:idfa];
        } else {
            [AppTools saveIDFA:@""];
        }
    }];
    
    if (@available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 无论结果如何都进入首页
            dispatch_async(dispatch_get_main_queue(), ^{
                [self gotoHomeScreen];
            });
        }];
    } else {
        // iOS 14以下直接进入首页
        [self gotoHomeScreen];
    }
}

#pragma mark - 进入首页
- (void)gotoHomeScreen {
    // 停止网络监控
    if (_pathMonitor) {
        nw_path_monitor_cancel(_pathMonitor);
        _pathMonitor = nil;
    }
    
    if ([AppTools isFirstOpen]) {
        GuideViewController *guideVC = [[GuideViewController alloc] init];
        guideVC.application = self.application;
        guideVC.launchOptions = self.launchOptions;
        [AppTools getWindow].rootViewController = guideVC;
    }else {
        // 切换到真实首页
        [AppStarPre toMain];
    }
}

@end
